package com.qianda.qdminiapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qianda.qdminiapp.common.constant.CommonConstant;
import com.qianda.qdminiapp.common.exception.ExceptionCode;
import com.qianda.qdminiapp.common.exception.SimpleException;
import com.qianda.qdminiapp.common.util.RandomUtil;
import com.qianda.qdminiapp.dao.account.QqdAccountTradeDao;
import com.qianda.qdminiapp.dao.order.QqdOrderInfoDao;
import com.qianda.qdminiapp.dao.order.QqdOrderRechargeDao;
import com.qianda.qdminiapp.dao.user.QqdUserDao;
import com.qianda.qdminiapp.domain.dto.PageRequest;
import com.qianda.qdminiapp.domain.model.account.QqdAccount;
import com.qianda.qdminiapp.dao.account.QqdAccountDao;
import com.qianda.qdminiapp.domain.model.account.QqdAccountTrade;
import com.qianda.qdminiapp.domain.model.order.QqdOrderInfo;
import com.qianda.qdminiapp.domain.model.order.QqdOrderRecharge;
import com.qianda.qdminiapp.domain.model.user.QqdUser;
import com.qianda.qdminiapp.service.OrderAndPaymentStrategy;
import com.qianda.qdminiapp.service.PaymentSelector;
import com.qianda.qdminiapp.service.QqdAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianda.qdminiapp.service.protocols.DeviceProtocolsV1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 账户表 服务实现类
 * </p>
 *
 * @author cw
 * @since 2019-08-14
 */
@Service
public class QqdAccountServiceImpl extends ServiceImpl<QqdAccountDao, QqdAccount> implements QqdAccountService {

    private static Logger LOGGER = LoggerFactory.getLogger(QqdAccountServiceImpl.class);

    @Autowired
    private QqdAccountDao qqdAccountDao;

    @Autowired
    private QqdUserDao qqdUserDao;

    @Autowired
    private QqdAccountTradeDao qqdAccountTradeDao;

    @Autowired
    private QqdOrderInfoDao orderInfoDao;

    @Autowired
    private QqdOrderRechargeDao qqdOrderRechargeDao;

    @Override
    public QqdAccount findAccount(Long userId) {
        QqdUser qqdUser = qqdUserDao.selectById(userId);
        if(qqdUser != null && qqdUser.getAccountId() != null){
            QqdAccount qqdAccount = qqdAccountDao.selectById(qqdUser.getAccountId());
            return qqdAccount;
        }else{
            throw  new SimpleException(ExceptionCode.EX_DEVICE_ACCOUNT_ERROR);
        }
    }

    @Override
    public IPage<QqdAccountTrade> findTradeList(Long userId, PageRequest pageRequest) {
        IPage<QqdAccountTrade >qqdAccountTradeIPage = new Page<>(pageRequest.getPage(),pageRequest.getSize());
         QueryWrapper<QqdAccountTrade> qqdAccountTradeQueryWrapper = new QueryWrapper<>();
         qqdAccountTradeQueryWrapper.eq("user_id",userId);
         qqdAccountTradeQueryWrapper.eq("status", CommonConstant.Status.STATUS_NORMAL);
         qqdAccountTradeQueryWrapper.orderByDesc("create_time");
        IPage<QqdAccountTrade> qqdAccountTradeIPages = qqdAccountTradeDao.selectPage(qqdAccountTradeIPage, qqdAccountTradeQueryWrapper);
        return qqdAccountTradeIPages;
    }

    @Override
    @Transactional
    public Map<String, Object> recharge(Long userId, BigDecimal rechargeAmt) {

        LOGGER.info("开始创建订单");
        String orderNo = RandomUtil.getId();
        //创建订单主表
        QqdOrderInfo qqdOrderInfo = new QqdOrderInfo();
        qqdOrderInfo.setOrderNo(orderNo);
        qqdOrderInfo.setOrderUserId(userId);
        qqdOrderInfo.setOrderType(CommonConstant.QqdOrderType.QQD_ORDER_TYPE_CHARGE);
        qqdOrderInfo.setOrderTime(LocalDateTime.now());
        qqdOrderInfo.setOrderAmt(rechargeAmt);
        qqdOrderInfo.setOrderRealAmt(rechargeAmt);
        qqdOrderInfo.setStatus(CommonConstant.Status.STATUS_NORMAL);
        qqdOrderInfo.setCreateTime(LocalDateTime.now());
        orderInfoDao.insert(qqdOrderInfo);

        QqdUser qqdUser = qqdUserDao.selectById(userId);

        QqdOrderRecharge qqdOrderRecharge = new QqdOrderRecharge();
        qqdOrderRecharge.setOrderId(qqdOrderInfo.getId());
        qqdOrderRecharge.setAccountId(qqdUser.getAccountId());
        qqdOrderRecharge.setOrderNo(qqdOrderInfo.getOrderNo());
        qqdOrderRecharge.setUserId(userId);
        qqdOrderRecharge.setOrderState(CommonConstant.RechargeOrderStatus.ORDER_STATUS_RECHARGING);
        qqdOrderRecharge.setRechargeAmt(rechargeAmt);
        qqdOrderRecharge.setStatus(CommonConstant.Status.STATUS_NORMAL);
        qqdOrderRecharge.setCreateTime(LocalDateTime.now());
        qqdOrderRechargeDao.insert(qqdOrderRecharge);

        //发起支付
        OrderAndPaymentStrategy orderAndPaymentStrategy = PaymentSelector.getPaymentSelector(CommonConstant.PayType.PAY_TYPE_WX);
        Map<String, Object> object = orderAndPaymentStrategy.appPay(qqdOrderInfo);
        return object;
    }

    @Override
    @Transactional
    public void rechargeOrder(QqdOrderInfo qqdOrderInfo) {
        //给用户账户加余额
        QueryWrapper<QqdOrderRecharge> qqdOrderRechargeQueryWrapper = new QueryWrapper<>();
        qqdOrderRechargeQueryWrapper.eq("order_no",qqdOrderInfo.getOrderNo()).eq("status",CommonConstant.Status.STATUS_NORMAL);
        QqdOrderRecharge qqdOrderRecharge = qqdOrderRechargeDao.selectOne(qqdOrderRechargeQueryWrapper);
        QqdAccount qqdAccount = qqdAccountDao.selectById(qqdOrderRecharge.getAccountId());
        qqdAccountDao.addBalance(qqdOrderRecharge.getAccountId(),qqdOrderInfo.getOrderAmt(),qqdAccount.getBalance());
        qqdOrderRecharge.setOrderState(CommonConstant.RechargeOrderStatus.ORDER_STATUS_RECHARG_SUCCESS);
        qqdOrderRechargeDao.updateById(qqdOrderRecharge);
    }
}
